package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.entity.UserInfo;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IBlogService;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserInfoService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {
    @Resource
    private IBlogService iBlogService;
    @Resource
    private IUserService iUserService;
    @Resource
    private IUserInfoService  iUserInfoService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Transactional
    @Override
    public Result followUser(Long id, Boolean isFollow) {

        //获取userId
        Long userId = UserHolder.getUser().getId();
        //获取blog作者的user_id
//        Blog blog = iBlogService.getById(id);
        Long blog_user_Id = id;
        String key = "follow_" + blog_user_Id;
        //isFollow是否关注
        if(isFollow){
            //准备关注
            boolean isExist = stringRedisTemplate.opsForSet().isMember(key,String.valueOf(userId));
            if(isExist){
                return  Result.fail("重复关注");
            }
            //1、user_id的用户followee+1，blog_user_id的用户 fans+1,同时写如tb_follow中
            UserInfo user = iUserInfoService.getById(userId);
            UserInfo follow_user = iUserInfoService.getById(blog_user_Id);
            //1.1判断是否存在在tb_user_info
            if(user==null){
                //添加到tb_user_info
                UserInfo userInfo = new UserInfo();
                userInfo.setUserId(userId);
                userInfo.setCreateTime(LocalDateTime.now());
                userInfo.setUpdateTime(LocalDateTime.now());
                log.debug("Inserting UserInfo: {}"+userInfo.toString());
                iUserInfoService.save(userInfo);
            }
            iUserInfoService.update().setSql("followee = followee + 1").eq("user_id", userId).update();
            if(follow_user==null){
               //添加到tb_user_info
                UserInfo userInfo = new UserInfo();
                userInfo.setUserId(blog_user_Id);
                userInfo.setCreateTime(LocalDateTime.now());
                userInfo.setUpdateTime(LocalDateTime.now());
                log.debug("Inserting UserInfo: {}"+userInfo.toString());
                iUserInfoService.save(userInfo);
            }
            iUserInfoService.update().setSql("fans = fans + 1").eq("user_id", blog_user_Id).update();
            //添加到tb_follow
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(blog_user_Id);
            follow.setCreateTime(LocalDateTime.now());
            save(follow);
            //写入redis 利用set集合,key为blog_user_id ，value为：user_id
            stringRedisTemplate.opsForSet().add(key,String.valueOf(userId));
        }else{
            boolean success = stringRedisTemplate.opsForSet().isMember(key,String.valueOf(userId));
            if(!success){
                return Result.fail("取消关注失败");
            }
            stringRedisTemplate.opsForSet().remove(key,String.valueOf(userId));
            iUserInfoService.update().setSql("followee = followee - 1").eq("user_id", userId).update();
            iUserInfoService.update().setSql("fans = fans - 1").eq("user_id", blog_user_Id).update();
            //删除tb_follow的东西
            remove(new QueryWrapper<Follow>()
                    .eq("user_id", userId).eq("follow_user_id", blog_user_Id));
        }

        return null;
    }

    @Transactional
    @Override
    public Result isFollow(Long followUserId) {
        // 1.获取登录用户
        Long userId = UserHolder.getUser().getId();
        // 2.查询是否关注 select count(*) from tb_follow where user_id = ? and follow_user_id = ?
//        Integer count = query().eq("user_id", userId).eq("follow_user_id", followUserId).count();
        String key = "follow_" + followUserId;
        boolean isExist = stringRedisTemplate.opsForSet().isMember(key,String.valueOf(userId));
        // 3.判断
        return Result.ok(isExist);
    }

    @Override
    public Result followCommons(Long id) {
        // 1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        String key = "follow_" + userId;
        // 2.求交集
        String key2 = "follow_" + id;
        //intersect redis的set集合的交集
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key, key2);
        if (intersect == null || intersect.isEmpty()) {
            // 无交集
            return Result.ok(Collections.emptyList());
        }
        // 3.解析id集合
        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        // 4.查询用户
        List<UserDTO> users = iUserService.listByIds(ids)
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(users);
    }


}
